/*
 * @Author: your name
 * @Date: 2022-04-26 15:55:04
 * @LastEditTime: 2022-04-27 10:29:19
 * @LastEditors: your name
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vite\src\store\Shops.ts
 */
import {defineStore} from 'pinia'
import getFood from "../commom/api"

interface food{
    id: string;
    title: string;
    price: number;
    nums: number;
}

interface foods {
    [inex:string]:food
}

export const shopStore = defineStore('shop',{
    state:()=>{
        return {
            foods:[] as Array<food>,
            isLoading:true,
        }
    },

    getters:{
        getShopObj(){
            let foods:foods = {};
             this.foods.forEach((item) => {
                foods[item.id] = item;
            });
            return foods;
        },

    },
    //开启持久化
	persist: {
		enabled: true,
		// storage:sessionStorage/localStorage,还可以自定义如下
		// https://seb-l.github.io/pinia-plugin-persist/
		// import Cookies from 'js-cookie'
		// const cookiesStorage: Storage = {
		//   setItem (key, state) {
		//     return Cookies.set('accessToken', state.accessToken, { expires: 3 })
		//   },
		//   getItem (key) {
		//     return JSON.stringify({
		//       accessToken: Cookies.getJSON('accessToken'),
		//     })
		//   },
		// }
		strategies: [
		      { storage: localStorage, paths: ['foods','isLoading'] }
		    ],
	},
 actions: {
    /**
     * 异步加载数据
     */
    async loadFoods() {
      this.foods = await getFood();
      this.isLoading = false;
    },
    /**
     * 加入购物车 商品数量减1
     * @param id
     */
    joinCard(id: string) {
      this.foods.forEach((item, index) => {
        if (item.id === id) {
          if (this.foods[index].nums > 0) {
            this.foods[index].nums--;
          }
        }
      });
    },
    /**
     * 购物车商品减少 商品数量加1
     * @param id
     */
    cardToShop(id: string) {
      this.foods.forEach((item, index) => {
        if (item.id === id) {
          this.foods[index].nums++;
        }
      });
    },
  }

})